
#include "http_server.h"

void main()
{
    http_server();
}

void http_server()
{
    printf("main http\n");
    // 端口
    int port = 12701;
    // 数量
    int size = 1;

    // 通讯
    int fd_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (fd_socket == -1)
    {
        perror("socket error");
        exit(-1);
    }
    // 地址
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(port);

    // 绑定
    if (bind(fd_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        perror("bind error");
        exit(-1);
    }

    // 监听
    if (listen(fd_socket, size) == -1)
    {
        perror("listen error");
        exit(-1);
    }

    printf("bind:%d\n", port);

    // 接受
    struct sockaddr_in client_addr;
    int addr_size = sizeof(client_addr);
    int fd_accept = accept(fd_socket, (struct sockaddr *)&client_addr, &addr_size);
    if (fd_accept == -1)
    {
        perror("accept error");
        exit(-1);
    }
    printf("conn:%s\n", inet_ntoa(client_addr.sin_addr));

    // 接收
    int max_len = 1024;
    char req[max_len];
    int req_len = recv(fd_accept, req, max_len - 1, 0);//默认传0
    if (req_len == -1)
    {
        perror("recv error");
        exit(-1);
    }else if (req_len == 0)
    {
        perror("recv empty");
        exit(-1);
    }
    else
    {
        req[req_len] = '\0';//字符串结束符
        printf("recv:%s\n", req);

        //HTTP协议
        char *line = strtok(req, "\r\n");
        while (line)
        {
            printf("strs:%s\n", line);
            line = strtok(NULL, "\r\n");
        }
        char resp[] = "HTTP/1.1 200 OK\r\n\r\nHelloWorld";
        int fd_send = send(fd_accept, resp, sizeof(resp) - 1, 0);//默认传0
        if (fd_send == -1)
        {
            perror("send error");
            exit(-1);
        }
    }


    // 关闭
    close(fd_accept);
    close(fd_socket);


    printf("main exit\n");
    exit(0);
}